package com.kinggrid.mybatisplus.pagination.configration;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.kinggrid.mybatisplus.pagination.configration.properties.MybatisPlusProperties;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

//Spring boot方式
@Configuration
@ConditionalOnClass(MybatisPlusInterceptor.class)
@EnableConfigurationProperties(MybatisPlusProperties.class)
@ComponentScan(basePackages = {"com.kinggrid.mybatisplus.pagination"})
@MapperScan("com.baomidou.cloud.service.*.mapper*")
public class MybatisPlusConfig {

    /**
     * 动态配置数据库分页插件方言
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    @RefreshScope
    public MybatisPlusInterceptor mybatisPlusInterceptor(MybatisPlusProperties mybatisPlusProperties) {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 默认使用MYSQL方言，如果需要更换请在properties配置中修改 dbType 和 dialect 方言参数
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        // 单页分页条数限制(默认无限制,参见 插件#handlerLimit 方法)
        // paginationInnerInterceptor.setMaxLimit(-1L);
        // 是否对超过最大分页时做溢出处理,true调回到首页，false 继续请求  默认false
        paginationInnerInterceptor.setOverflow(false);
        // 设置数据库类型
        String dbTypeStr = mybatisPlusProperties.getDataBase().getDateBaseType();
        // 查找应该配置的数据库类型
        DbType dbType = DbType.getDbType(dbTypeStr);
        paginationInnerInterceptor.setDbType(dbType);
        // 设置分页方言, 不设置会根据dbType自动设置
        // paginationInnerInterceptor.setDialect();
        // 优化Join分页语句，现在只支持Left Join，默认true
        paginationInnerInterceptor.setOptimizeJoin(true);

        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }
    
}